<?php

namespace App\Models;

use App\Models\BlackModel;
use App\Models\ComModel;

/**
 * 后台必须模型
 */
class AdminModel extends ComModel
{
    public $tablename;

    public function __construct(...$param)
    {
        parent::__construct();
        $this->tablename = 'admin';
    }

    // 后台管理员登录
    public function login($username, $password)
    {
        $data = $this->db->table('admin')->where('username', $username)->where('unlock<' . time())->limit(1)->get()->getRowArray();
        $password = esc($password);
        // 判断用户状态
        if (!$data || (md5(sha1($password) . $data['salt'] . md5($password)) != $data['password'])) {
            if ($data && defined('SITE_ADMIN_LOCK') && SITE_ADMIN_LOCK) {
                if ($data['islock'] >= SITE_ADMIN_LOCK) {
                    $rt['msg'] = SITE_ADMIN_LOCK . '次登录错误后,将锁定账号!';
                    $unlock = time() + SITE_ADMIN_LOCK_HOUR * 3600;
                    $this->db->table($this->tablename)->where('uid', $data['uid'])->update(['unlock' => $unlock]);
                    //ip加黑名单
                    $unlock = date('Y-m-d', $unlock);
                    $ip = $this->request->getIPAddress();
                    $black = new BlackModel();
                    $rt = $black->add(['ip' => $ip, 'endtime' => $unlock]);
                    return ams_rt(1, '账号或IP可能已经锁定');
                } else {
                    $this->db->table($this->tablename)->where('uid', $data['uid'])->set('islock', 'islock+1', false)->update();
                }
            }
            return ams_rt(1, '账号或者密码错误');
        }
        $this->db->table($this->tablename)->where('uid', $data['uid'])->update(['islock' => 0, 'unlock' => 0]);

        $adminid = $data['uid'];
        $roleid = (int) $data['roleid'];
        // 查询角色组
        $role = $this->_role($roleid);
        if (!$role) {
            return ams_rt(1,'您的账号已失效');
        }
        // 管理员登录日志记录
        $this->_login_log($adminid);

        // 保存会话
        $this->session->set('adminid', $adminid);
        $this->session->set('admin', $data);
        ams_set_cookie('adminid', $adminid, WEEK);
        ams_set_cookie('admin_cookie', substr(md5(SITE_KEY . $data['password']), 5, 20), WEEK);
        return ams_rt(0, 'OK', $adminid);
    }

    //退出
    public function logout()
    {
        $this->session->remove('adminid');
        $this->session->remove('admin');
        delete_cookie('adminid');
        delete_cookie('admin_cookie');
        return ams_rt(0, 'ok');
    }

    public function get_adminid()
    {
        $adminid = $this->session->get('adminid');
        // $adminid = ams_get_cookie('adminid');
        if (!$adminid) {
            return 0;
        }
        return $adminid;
    }

    public function get_admin($id = 0)
    {
        $id = intval($id);
        // 查询用户信息
        $data = $this->db->table('admin')->where('uid', $id)->get()->getRowArray();
        if (!$data) {
            return ams_rt(1, '数据不存在');
        }
        //查询权限
        return ams_rt(0, 'OK', $data);
    }

    /**
     * 验证会员有效性 1表示通过 0表示不通过
     */
    public function check_admin_cookie($admin)
    {
        // 获取本地认证cookie
        $cookie = $this->request->getCookie('admin_cookie');
        // 授权登陆时不验证
        if (isset($admin['uid']) && $this->session->get('adminid') == $admin['uid']) {
            return 1;
        } elseif (!$cookie) {
            return 0;
        } elseif (substr(md5(SITE_KEY . $admin['password']), 5, 20) !== $cookie) {
            return 0;
        }
        return 1;
    }

    // 获取当前管理员的角色组id
    private function _role($role_id)
    {
        $role = $this->db->table('rbac_role')->where('id', $role_id)->where('status', 1)->get()->getResultArray();
        if (!$role) {
            return false;
        }
        return $role;
    }

    /**
     * 登录记录
     */
    private function _login_log($uid)
    {

        $ip = $this->request->getIPAddress();
        if (!$ip || !$uid) {
            return;
        }

        $agent = $this->request->getUserAgent();
        if (strlen($agent) <= 5) {
            return;
        }

        $data = [
            'uid' => $uid,
            'loginip' => $ip,
            'logintime' => time(),
            'useragent' => substr($agent, 0, 255),
        ];

        // 同一天Ip一致时只更新一次更新时间 今天
        $row = $this->db->table('admin_login')->where('uid', $uid)->where('loginip', $ip)->where('DATEDIFF(from_unixtime(logintime),now())=0')->get()->getRowArray();
        if ($row) {
            $this->db->table('admin_login')->where('id', $row['id'])->update($data);
        } else {
            $this->db->table('admin_login')->insert($data);
        }

    }

}
